package net.wenku8.reader.util

import android.annotation.SuppressLint
import android.icu.text.SimpleDateFormat
import android.util.Log
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.security.AnyTypePermission
import java.security.MessageDigest
import java.util.Date


fun hasValue(str : String?) : Boolean{
    return str != null && str.trim().isNotEmpty()
}

fun isEmpty(str : String?) : Boolean{
    return !hasValue(str)
}

fun isInt(str : String) : Boolean{
    return Regex("\\d+").matches(str)
}

fun toInt(str : String?) : Int{
    if (str == null || !isInt(str)){
        return 0
    }
    return Integer.getInteger(str)?.toInt() ?: 0
}

fun <T> parseXml(body: String?, respClass: Class<T>): T? {
    if (body == null){
        return null
    }
    return try {
        var xml = body
        if (body.startsWith("<?xml")) {
            val i: Int = body.indexOf(">")
            xml = body.substring(i + 1)
        }
        val xStream = XStream()
        xStream.addPermission(AnyTypePermission.ANY)
        xStream.processAnnotations(respClass)
        xStream.autodetectAnnotations(true)
        return xStream.fromXML(xml) as? T
    } catch (e: Throwable) {
        Log.i("parseXml", "", e)
        null
    }
}

fun String.lowerFirst(): String {
    if (isNotEmpty()) {
        val firstChar = this[0]
        if (firstChar.isUpperCase()) {
            return "${firstChar.lowercase()}${substring(1)}"
        }
    }
    return this // 如果已经是小写或为空，则直接返回原字符串
}


@SuppressLint("SimpleDateFormat")
fun formatTime(time : Date): String{
    val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return sdf.format(time);
}


@SuppressLint("SimpleDateFormat")
fun formatDate(time : Date): String{
    val sdf = SimpleDateFormat("yyyy-MM-dd");
    return sdf.format(time);
}


@SuppressLint("SimpleDateFormat")
fun formatTimeNum(time : Date): String{
    val sdf = SimpleDateFormat("yyyyMMddHHmmssSSS");
    return sdf.format(time);
}

fun getMd5(text: String ?): String? {
    if (text == null) return null
    try {
        val md = MessageDigest.getInstance("MD5")
        md.update(text.toByteArray())
        val b = md.digest()
        return bytesToHexStr(b)
    } catch (e: Exception) {
        Log.e("", "getMd5", e)
    }
    return null
}


fun bytesToHexStr(b: ByteArray): String {
    val str = StringBuilder()
    for (i in 0 until b.lastIndex) {
        str.append(String.format("%02x", *arrayOf<Any>(b[i])))
    }
    return str.toString()
}